package
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.filesystem.*;
	import flash.filters.BlurFilter;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import flash.geom.Point;
	import flash.utils.ByteArray;
	
	import mx.graphics.codec.PNGEncoder;

	public class FileHandle
	{
		private static var pngEncoder:PNGEncoder = new PNGEncoder();
		
		/**
		 * 保存 
		 * @param fileName
		 * @param data
		 * 
		 */		
		public static function save(fileName:String, data:*) : void
		{
			var bytes:ByteArray = formatToByteArray(data);
			
			var fileStream:FileStream = new FileStream();

			var file:File = new File(fileName);
			fileStream.open(file, FileMode.WRITE);
			fileStream.addEventListener(Event.COMPLETE, onIoComplete);
			fileStream.writeBytes(bytes);
		}
		
		private static function onIoComplete(e:Event) : void
		{
			e.target.removeEventListener(Event.COMPLETE, onIoComplete);
			e.target.close();
		}
		
		/**
		 * 格式化成二进制数组 
		 * @param data：{bitmap 或者 bitmapData}
		 * @return 
		 * 
		 */		
		public static function formatToByteArray(data:*) : ByteArray
		{
			var bitmapData:BitmapData;
			if (data is Bitmap)
			{
				bitmapData = data.bitmapData;
			}
			else if (data is BitmapData)
			{
				bitmapData = data;
			}
			else
			{
				throw new Error("传进参数类型不对");
			}
			
			var bytes:ByteArray = pngEncoder.encode(bitmapData);
			
			return bytes;
		}
		
		/**
		 * 获取文件名 
		 * @param url（路径）
		 * @return 
		 * 
		 */		
		public static function getFileName(url:String) : String
		{
			var flag:int = url.lastIndexOf("/");
			var fileName:String = url.substr(flag + 1, url.length);
			
			return fileName;
		}
		
		/**
		 * 缩放 
		 * @param bitmap: 原对象
		 * @param value ： 缩放比例
		 * @return 
		 * 
		 */		
		public static function scaleTwo(bitmapData:BitmapData, scaleNum:Number) : Bitmap
		{
			var w:uint = bitmapData.width * scaleNum;
			var h:uint = bitmapData.height * scaleNum;
			
			var bd:BitmapData = new BitmapData(w, h, true, 0x00000000);
			
			var matrix:Matrix = new Matrix();
			matrix.scale(scaleNum, scaleNum);
			
			bd.draw(bitmapData, matrix, null, null, null, true);

			return new Bitmap(bd, "auto", true);
		}
		
		public static function scale(bmd:BitmapData, scale:Number) : Bitmap
		{
			var bm : Bitmap = new Bitmap(bmd, "auto", true);
			bm.width = Math.round(bmd.width * scale);
			bm.height = Math.round(bmd.height * scale);
			
			var sp : Sprite = new Sprite();
			sp.addChild(bm);
			
			var newBmd:BitmapData = new BitmapData(sp.width, sp.height, true, 0x00000000);
			newBmd.draw(sp);
			
			return new Bitmap(newBmd, "auto", true);
		}
	}
}